<template>
	<view class="content">
		<!-- 顶部自定义导航 -->
		<tn-nav-bar fixed :bottomShadow="false" backTitle=" ">
		  <view class="" >
		    <text class="tn-text-lg">{{title}}</text>
		   <!-- <text class="tn-text-xl tn-padding-left-sm tn-icon-group-circle"></text>  -->
		  </view>
		</tn-nav-bar>
		
		<view class="content-box" @touchstart="touchstart" id="content-box" :class="{'content-showfn':showFunBtn}">
			<!-- 背景图- 定位方式 -->
			<!-- <view class="content-box-loading" v-if="!loading"><u-loading mode="flower"></u-loading></view> -->
			
			<mescroll-body ref="mescrollRef" bottom="10%" @init="mescrollInit" :down="downOption" @down="downCallback" :up="upOption">
			
			<view class="message" v-for="(item, index) in messageList" :key="index" :id="`msg-${item.id}`">
				<view class="message-item " :class="!item.isItMe ? 'right' : 'left'">
					
					<!-- 图像昵称 -->
					<view v-if="item.contentType != 101" class="username">
						<!-- <text class="ttt" color="#6c6c6c" align="center">{{item.fromUserName}}</text> -->
						<image class="logo" :src="item.fromUserHeadImg" @click.stop="tn('/circlePages/king?userId='+item.userId)"></image>
					</view>
					
					<!-- contentType = 1 文本 -->
					<view class="content" v-html="transformHtml(item.content)" v-if="item.contentType == 0">
					</view>
					
					<view class="notice" v-if="item.contentType == 101">
						{{ item.content }} 
					</view>
					
				</view>
				
			</view> 
			
			</mescroll-body>
			
		</view>
		
		<!-- 底部聊天输入框 -->
		<view class="input-box" :style="{ bottom: bottom}" :class="{ 'input-box-mpInputMargin': mpInputMargin }">
			<view class="input-box-flex">
				<view class="input-box-flex-grow"> 
					<input
						v-if="chatType === 'keyboard'"
						type="text"
						class="content"
						id="input"
						:disabled="showFunBtn"
						:adjust-position="false" 
						v-model="formData.content"
						:hold-keyboard="true"
						:confirm-type="'send'"
						:confirm-hold="true"
						placeholder-style="color:#DDDDDD;"
						:cursor-spacing="10"
						@confirm="sendMsg(null)"
						@focus="focusInput"
						@blur="blurInput"
					/>
				</view>
				
				<!-- 功能性按钮 -->
				<view v-show="formData.content == ''" class="iconfont icontianjia icon_btn_add" @tap="switchFun"></view>
				<button v-show="true" type="primary" class="icon_btn_add" size="mini" @touchend.prevent="sendMsg(null)">发送</button>
			</view>
			
			<view class="fun-box" :class="{'show-fun-box':showFunBtn}">
				<swiper
				                :indicator-dots="true"
				                class="swiper"
				        >
				            <!-- <swiper-item>
								<u-grid :col="5" hover-class="contentType2-hover-class" :border="false" @tap="clickGrid">
									<u-grid-item v-for="(item, index) in btns" :index="index" :key="index">
										 <u-icon
												:customStyle="{paddingTop:20+'rpx'}"
												:name="item.url"
												:size="60"
												 ></u-icon>
										<text class="grid-text">{{ item.title}}</text>
									</u-grid-item>
								</u-grid>
				            </swiper-item> -->
							<swiper-item>
								<face @addEmoji="addEmoji" @delEmoji="delEmoji"></face>
							</swiper-item>
				</swiper>
			</view>

		</view>
		
		
		<!-- 打开卡片窗口 -->
		<wind :packet="packet" :winState="winState" @close="closeCard" @open="openCard"></wind>
		<tn-toast ref="toast"></tn-toast>
	</view>
</template>

<script>
import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js"
import template_page_mixin from '@/libs/mixin/template_page_mixin.js'
import face from '@/components/face'
import base from '@/common/config.js'
import avatar from '@/components/avatar'
import { transform } from '@/common/ChatUtils.js';
import request from "@/common/request.js"
 import webim from '@/common/socket/webim.js'

export default {
	mixins: [MescrollMixin, template_page_mixin], // 使用mixin
	components:{face,avatar},
	data() {
		return {
			winState:'',
			webUrl:base.webUrl,
			isTop: false,
			pShow:false,
			downOption:{
				auto:false,
				autoShowLoading: true, // 显示下拉刷新的进度条
				textColor: "#00aaff" // 下拉刷新的文本颜色
			},
			upOption: {
				use: false, // 禁止上拉
				toTop: {
					src: '' // 不显示回到顶部按钮
				}
			},
			value: false,
			packet:{},
			chatObj:{
				chatName:"与xxx的聊天"
			},
			user:{},
			toUserId:0,
			req:{
				chatId:0,
				recordId:''
			},
			formData: {
				content: '',
				limit: 10,
				index: 2
			},
			messageList: [],
			message:{
				hasBeenSentId:0
			},
			bottom:0,
			loading: true, 
			//标识是否正在获取数据
			imgHeight: '1000px',
			mpInputMargin: false, 
			//适配微信小程序 底部输入框高度被顶起的问题
			chatType:"keyboard",  
			showFunBtn:false, //是否展示功能型按钮
			ListItem:[],
			btns: [],
			title:''
		};
	},
	
	methods: {
		focusInput(e){
			this.bottom  = e.detail.height + "px"
			this.scrollEnd()
		},
		blurInput(){
			this.bottom = 0
			this.scrollEnd()
		},
		tn(e) {
			uni.navigateTo({
				url: e,
			});
		},
		 downCallback() {
			 
		    // 这里写下拉时需要执行的逻辑代码
			if(this.messageList[0].contentType ==  101){
				this.req.recordId = this.messageList[1].id
			}else{
				this.req.recordId = this.messageList[0].id
			}
			
			request.post("friend/wx/chatCenter/selectChatRecord",this.req).then(res=>{
				let _data = res[1]['data']
				
				if(_data.code == 20000){
					let res = _data.data
					if(res.length > 0){
						let _d = this.makeData(res.sort(function(a, b){return Number(a.id)-Number(b.id)}));
						this.messageList = _d.concat(this.messageList)
						
						this.$nextTick(() => {
							this.mescroll.scrollTo(44, 0);
							//this.loading = true;
						});
					}else{
						 this.$refs.toast.show({
						    title: '',
							content: '没有更多消息了',
							//icon: 'success',
							image: '',
							duration: 1500
						})
					}
					
					this.mescroll.endErr();
					
				}
			})
			
		    // 模拟加载完成后结束下拉动作
		    setTimeout(() => {
		      uni.stopPullDownRefresh();
		    }, 1000);
		  },
		//...mapMutations(['setPacketData','setUserCardData','setPacketPush','setGroupMembers','setChatObj']),
		// 表情
		addEmoji(item){
			this.ListItem.push(item);
			this.formData.content = this.formData.content + "face" + item;
		},
		delEmoji(){
		},
		transformHtml(content){
			return transform(content)
		},
		
		closeCard(){
			this.winState = 'hide';
			setTimeout(()=>{
				this.winState = '';
			},200)
		},
		
		makeData(res){
			let _res = [];
			for(var i =0; i<res.length;i++){
				_res.push({
					id:res[i].id,
					chatType: 0,
					content: res[i].msgContent,
					contentType: 0,
					createTime: res[i].createTime,
					fromUserHeadImg: res[i].headUrl,
					fromUserId: res[i].userId,
					fromUserName: "",
					isItMe: res[i].left,
					userId: res[i].userId
				})
			}
			
			return _res;
		},
		// 初始消息数据
		async initData() {
			let _that = this
			
			request.post("friend/wx/chatCenter/selectChatRecord",this.req).then(res=>{
				let _data = res[1]['data']
				
				if(_data.code == 20000){
					let res = _data.data
					
					this.messageList = this.makeData(res.sort(function(a, b){return Number(a.id)-Number(b.id)}));
					
					let _c = this.messageList.length
					
					if(this.req.recordId == '' && _c == 0){
						// 初始化聊天窗口
						this.messageList.push({
							id:0,
							chatType: 0,
							content: '为保护他（她）人隐私，只有相互喜欢后方可聊天，请勿发送违规信息！',
							contentType: 101,
						})
					}
					
					
					if(_c != 0){
						_that.$nextTick(() => {
							_that.scrollEnd()
							
							_that.loading = true;
						});
					}
					
				}
			})
			
		},
		
		scrollEnd(){
			if(this.messageList.length < 11){return true;}
			this.mescroll && this.bindScroll(this.messageList[this.messageList.length-1].id);
		},
		//处理滚动
		bindScroll(hasBeenSentId, duration = 0) {
			let view = uni.createSelectorQuery().select('#msg-'+ hasBeenSentId);
			
			view.boundingClientRect(v => {
				this.mescroll.scrollTo(v.top - 100, 0) // 减去上偏移量100
			}).exec();
		},
		//切换语音或者键盘方式
		switchChatType(type) {
			this.chatType = type;
			this.showFunBtn =false;
		},
		//切换功能性按钮
		switchFun(){
			this.chatType = 'keyboard'
			this.showFunBtn = !this.showFunBtn;
			uni.hideKeyboard();
			this.$nextTick(() => {
				this.mescroll.scrollTo(999999, 0);
			});
		},
		
		switchContentType(data, params){
			let _t = this;
			if (data) {
				// 视频
				if(data.contentType == 1){
					params.content = data.content;
					params.contentType = 1;
				}else if(data.contentType == 2){
					//说明是发送语音
					params.contentType = 2;
					params.content = data.content;
					params.anmitionPlay = false;
				}else if(data.contentType == 3){
					//发送图片
					params.content = data.content;
					params.contentType = 3;
				} 
			}
			params.contentType = 0;
			// 目前 contentType 只有 0 
			if(params.contentType == 0){
				if(_t.formData.content!=''){
					
					if(!_t.isTop){
						if(_t.messageList.length>=10){
							_t.messageList.splice(0,1);
						} 
					}
					
					params.content = params.content || params.msg;
					params.chatType = 0;
					params.contentType = 0;
					params.isItMe = false;
					params.fromUserHeadImg = this.user.url;
					
					_t.messageList.push(params);
				}
			} else {
				/* if(!_t.isTop){
					if(_t.messageList.length>=10){
						_t.messageList.splice(0,1);
					} 
				}
				_t.messageList.push(params);
				
				let reqData = {
					chatId: _t.chatObj.chatId,
					chatType:_t.chatObj.chatType,
					userId: _t.user.operId,
					message: params.content,
					msgType: params.contentType
				}
				
				reqChat.msgAdd(reqData).then(res=>{
				}); */
			}
		},
		//发送消息
		sendMsg(data) {
			let _t = this
			
			_t.isTop = false;
			
			const params = {
				msg: _t.formData.content,
				toUserId: _t.toUserId,
				fromUserId: _t.user.id
			};
			
			// this.switchContentType(data, params);
			
			// 发送消息到服务器转发
			_t.$socket.sendMessage(params, res=>{
				// 没有会话内容 表示用户已经离开聊天窗口
				if(_t.req.chatId != undefined){
					var _d = this.makeData([res.memberChatRecord])
					var _m = _d[0]
					_m.fromUserHeadImg = _t.user.url
					_m.fromUserId = _t.user.id
					this.messageList.push(_m)
					
				
				}
			});
			
			_t.$nextTick(() => {
				_t.formData.content = '';
					
				if(!_t.isTop){
					_t.scrollEnd()
				}
				
				if(_t.showFunBtn){
					_t.showFunBtn = false;
				}
				
				// #ifdef MP-WEIXIN 
				if (params.contentType == 1) {
					_t.mpInputMargin = true;
				} 
				// #endif
				//h5浏览器并没有很好的办法控制键盘一直处于唤起状态 而且会有样式性的问题
				// #ifdef H5
				uni.hideKeyboard();
				// #endif
			});
		},
		
		receiveMsg(res){
			let _t = this
			console.log("ccccccccccccccccccccccccc")
			console.log(res)
			if(this.toUserId == res.fromUserId){
				var _d = this.makeData([res.memberChatRecord])
				this.messageList.push(_d[0])
				if(!_t.isTop){
					_t.mescroll && _t.mescroll.scrollTo(99999, 0);
				}
			}
		},
		//用户触摸屏幕的时候隐藏键盘
		touchstart() {
			uni.hideKeyboard();
			this.showFunBtn =false;
		},
		// 卡片
		linkCard(item) {
			item.id = item.userId
			item.source = 0
			item.nickName = item.fromUserName
			item.avatar = item.fromUserHeadImg
			this.setUserCardData(item);
			this.$u.route({
				url: '/pages/friend/businessCard'
			});
		},
		
		//关闭动画
		closeAnmition() {
			const hasBeenSentId = this.Audio.hasBeenSentId;
			const item = this.messageList.find(it => it.hasBeenSentId == hasBeenSentId);
			item.anmitionPlay = false;
		},
		//点击宫格时触发
		clickGrid(index){
			if(index == 0){
				this.chooseImage(['album'])
			}else if(index == 1){
				this.chooseImage(['camera'])
			}else if(index == 2){
				this.pShow = true;
			} else if(index == 3){
				// 上传可以不用传递url（使用全局的上传图片url）
				this.$http.urlVideoUpload({
				}).then(res=>{
					this.showFunBtn = false;
					const params = {
						contentType: 1,
						content: res,
					};
					this.sendMsg(params);
				});
			}
		},
		//发送图片
		chooseImage(sourceType){
			$http.urlImgUpload({
				sourceType:sourceType
			}).then(res=>{
				this.showFunBtn = false;
				const params = {
					contentType: 3,
					content: res,
				};
				this.sendMsg(params);
			});
		},
		//查看大图
		viewImg(imgList){
			uni.previewImage({
				urls: imgList,
				// #ifndef MP-WEIXIN
				indicator: 'number'
				// #endif
			});
		}
		
	},
	
	//返回按钮事件
	onBackPress(e) {
	},
	onLoad(info) {
		this.req.chatId = info.chatId
		this.toUserId = info.toUserId
		this.webUrl = base.webUrl;
		this.title = "与 " + info.name + " 的对话"
		this.user = uni.getStorageSync("userInfo")
		let _t = this
		
		/* if(!this.user || this.user === undefined || this.user == null){
			uni.navigateTo({
			    url: '/minePages/login'
			});
		}
		
		let id = this.user.id
		let packet = {
			id,
			version: 1,
			command: 1
		}
		webim.initSocket(packet); */
		
		
		uni.$on("receiveMsg",function(res){
			_t.receiveMsg(res)
		})
	},
	onUnload() {
		// 离开以后一定要赋值空
		//this.setChatObj({});
	},
	onReady() {
		
		let _this = this
		
		_this.initData();
		
		uni.getSystemInfo({
			success: res => {
				this.imgHeight = res.windowHeight + 'px';
			}
		});
		
		uni.onKeyboardHeightChange(res => {
			if (res.height == 0) {
				// #ifdef MP-WEIXIN
				this.mpInputMargin = false;
				// #endif
			}else{
				this.showFunBtn = false;
			}
		});
	}
};
</script>

<style lang="scss" scoped>
	.content image{
		width: 30rpx;
		height:30rpx
	}
	.ttt{font-weight: bold;}
	.content image.logo{
		width: 80rpx;
		height: 80rpx;
		border-radius: 40rpx;
	}
	.notice{
		color: #909399;
		width: 100%;
		text-align: center;
	}
	.grid-text {
		font-size: 14px;
		color: #909399;
		padding: 10rpx 0 20rpx 0rpx;
		/* #ifndef APP-PLUS */
		box-sizing: border-box;
		/* #endif */
	}
 @import './index.scss'
</style>
